import knowService from '@/api/services/knowService';
import Modals from '@/components/modals/Modals';
import { DatePicker, message } from 'antd';
import { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { useContextSelector } from 'use-context-selector';
import { DatasetsContext } from '../context';
import datasetService from '@/api/services/datasetService';

interface Props {
  open: boolean;
  placeholder?: string;
  onCancel?: () => void;
  onOk?: () => void;
}

const ExpirationTimeModal = ({ open, onCancel, onOk, ...props }: Props) => {
  const { updateExpiredTime } = useContextSelector(DatasetsContext, (s) => s);
  const [dateString, setDateString] = useState('');
  const [newDateString, setNewDateString] = useState('');
  const [defaultDate, setDefaultDate] = useState<string | undefined>(undefined);
  const onDateChange = (dateString: string | string[]) => {
    if (!Array.isArray(dateString)) {
      setDateString(dateString);
    }
  };

  const disabledDate: RangePickerProps['disabledDate'] = (current) => {
    return current && current < dayjs(undefined).endOf('day');
  };

  useEffect(() => {
    if (updateExpiredTime?.experiodDays != null) {
      setDefaultDate(dayjs(updateExpiredTime.experiodTimes).format('YYYY-MM-DD HH:mm:ss'));
    } else {
      setDefaultDate(undefined);
    }
    setDateString('');
    setNewDateString('');
  }, [updateExpiredTime, open]);

  const onOkClicked = async () => {
    if (defaultDate) {
      if (newDateString) {
        try {
          await knowService.postUpdateExpired({
            collection_id: updateExpiredTime!.collectionId!,
            expired_time: newDateString,
          });
          message.success('修改过期时间成功');
          onOk?.();
        } catch (error) {
          message.error('修改过期时间失败');
        }
        onCancel?.();
      }
    } else {
      if (dateString) {
        try {
          await knowService.postUpdateExpired({
            collection_id: updateExpiredTime!.collectionId!,
            expired_time: dateString,
          });
          message.success('添加过期时间成功');
          onOk?.();
        } catch (error) {
          message.error('添加过期时间成功');
        }
        onCancel?.();
      }
    }
  };
  const onDeleteClicked = async () => {
    try {
      await datasetService.delCollectionMetadata({
        collection_id: updateExpiredTime!.collectionId!,
        metadata: ['expiredTime'],
      });
      message.success('删除过期时间成功');
      onOk?.();
    } catch (error) {
      message.error('删除过期时间失败');
    }
    onCancel?.();
  };

  return (
    <Modals
      onCancel={onCancel}
      open={open}
      onOk={onOkClicked}
      {...props}
      title={defaultDate ? '修改过期时间' : '添加过期时间'}
    >
      {defaultDate ? (
        <div>
          <div className="mb-2 font-semibold">新的过期时间</div>
          <DatePicker
            className="w-full"
            value={newDateString ? dayjs(newDateString) : dayjs(defaultDate)}
            disabledDate={disabledDate}
            onChange={(_, dataString) => {
              setNewDateString(`${dataString} 23:59:59`);
            }}
            allowClear={false}
            placeholder="请选择新的过期时间"
          />
        </div>
      ) : (
        <div>
          <div className="mb-2 font-semibold">过期时间</div>
          <DatePicker
            className="w-full"
            value={dateString ? dayjs(dateString) : undefined}
            disabledDate={disabledDate}
            onChange={(_, dataString) => {
              onDateChange(`${dataString} 23:59:59`);
            }}
            allowClear={false}
            placeholder="请选择过期时间"
            // showTime
          />
        </div>
      )}
    </Modals>
  );
};

export default ExpirationTimeModal;
